package com.company.project.web;

import com.company.project.core.Result;
import com.company.project.core.ResultGenerator;
import com.company.project.model.VO.LoginVO;
import com.company.project.model.VO.UserVO;
import com.company.project.model.VtManager;
import com.company.project.service.LoginService;
import com.company.project.util.JWTUtils;
import com.company.project.util.MD5Utils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


@RestController
@RequestMapping("/login")
public class LoginController {
    @Resource
    private LoginService loginService;
//    @PostMapping("/login")
//    public Result login(String userName, String passWord) {
//        System.out.println(userName);
//        return loginService.login(userName,passWord);
//    }
    @PostMapping("/login")
    public Result login(@RequestBody LoginVO loginVO) {
        System.out.println(loginVO.getUserName());
        if (loginVO.getUserName().isEmpty()) return ResultGenerator.genFailResult("请输入用户名");
        if (loginVO.getPassWord().isEmpty()) return ResultGenerator.genFailResult("请输入密码");
        VtManager vtManager = loginService.getUser(loginVO.getUserName(),loginVO.getPassWord());
        if (Objects.isNull(vtManager)) return ResultGenerator.genFailResult("没有当前用户，请联系管理员！");

        if (!MD5Utils.verifyPassword(vtManager.getPassword(),vtManager.getPasssalt(),loginVO.getPassWord())) {
            return ResultGenerator.genFailResult("密码错误，请联系管理员！");
        }
        
        Map<String,String> map = new HashMap<>();
        map.put("userId",vtManager.getUserid().toString());
        map.put("username",vtManager.getUsername());
        String token = JWTUtils.getToken(map);
        UserVO userVO = new UserVO();
        userVO.setUserId(vtManager.getUserid());
        userVO.setRoleId(vtManager.getRoleid());
        userVO.setGroupId(vtManager.getGroupid());
        userVO.setTrueName(vtManager.getTruename());
        userVO.setGender(vtManager.getGender());
        userVO.setNickName(vtManager.getNickname());
        userVO.setUserName(vtManager.getUsername());
        userVO.setToken(token);
        return ResultGenerator.genSuccessResult(userVO);
    }
}
